#include "widget.h"
#include "ui_widget.h"
#include <QNetworkDatagram>
#include <QShortcut>
#include <QDebug>

const QString SERVER_IP = "110.40.209.26";
const quint16 SERVER_PORT = 8080;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //设置窗口标题
    this->setWindowTitle("客户端");

    //创建udp服务器
    udp = new QUdpSocket(this);

    //创建QShortcut对象
    QShortcut * shortcut = new QShortcut(QKeySequence(Qt::Key_Return),this);

    //绑定按钮信号槽
    connect(shortcut,&QShortcut::activated,ui->pushButton,&QPushButton::click);


    //绑定信号槽
    connect(udp,&QUdpSocket::readyRead,this,&Widget::handleResponse);


}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
     //获取到edit的文本
    const QString &request = ui->lineEdit->text();

    //构建请求数据包
    QNetworkDatagram dataGramRequest(request.toUtf8(),QHostAddress(SERVER_IP),SERVER_PORT);

    //将数据包进行发送
    udp->writeDatagram(dataGramRequest);

    //将发送的响应信息显示到控件上
    ui->listWidget->addItem("client say# " + request);

    //将edit上的文本清空
    ui->lineEdit->setText("");
}

void Widget::handleResponse()
{
    //接收服务器发送来的响应报文
    const QNetworkDatagram &dataGramResponse = udp->receiveDatagram();
    //对报文内容进行解析
    QString response = "server echo@ " + dataGramResponse.data();
    //显示到控件上
    ui->listWidget->addItem(response);
}

